// Auteur : Simon-Pierre Boucher — contact@spboucher.ai
// Profil public d'un membre (opt-in) — groupe-ka.com/u/{ka_id}.
// Affiche nom, photo, statut, bio, emploi, ville, âge, site et réseaux —
// JAMAIS le courriel ni le téléphone. 404 indistinct si privé/inexistant.
import type { Metadata } from "next";
import {
  db,
  parseSocials,
  ageFromBirthDate,
  type UserRow,
} from "@/lib/db";
import { roleCard } from "@/lib/roles";

export const metadata: Metadata = {
  title: "Profil de membre | Groupe KA",
  description: "Profil public d'un membre du Groupe KA.",
};

export const dynamic = "force-dynamic";

function fmtDate(iso: string | null): string {
  if (!iso) return "—";
  const d = new Date(iso.includes("T") ? iso : iso.replace(" ", "T") + "Z");
  if (Number.isNaN(d.getTime())) return "—";
  return d
    .toLocaleDateString("fr-CA", { month: "long", year: "numeric" });
}

const SOCIAL_LABELS: Record<string, string> = {
  instagram: "Instagram",
  facebook: "Facebook",
  x: "X",
  linkedin: "LinkedIn",
  tiktok: "TikTok",
  youtube: "YouTube",
};

function socialHref(key: string, value: string): string {
  if (/^https?:\/\//i.test(value)) return value;
  const handle = value.replace(/^@/, "");
  const base: Record<string, string> = {
    instagram: "https://instagram.com/",
    facebook: "https://facebook.com/",
    x: "https://x.com/",
    linkedin: "https://www.linkedin.com/in/",
    tiktok: "https://www.tiktok.com/@",
    youtube: "https://www.youtube.com/",
  };
  return (base[key] ?? "https://") + handle;
}

export default async function ProfilPublic({
  params,
}: {
  params: Promise<{ kaId: string }>;
}) {
  const { kaId } = await params;
  const clean = /^ka-\d{10}$/.test(kaId) ? kaId : null;
  const row = clean
    ? (db.prepare("SELECT * FROM users WHERE ka_id = ?").get(clean) as
        | UserRow
        | undefined)
    : undefined;

  // privé ou inexistant : indistinguable, volontairement
  if (!row || !row.public) {
    return (
      <main className="mx-auto max-w-md px-4 pb-16 sm:px-6">
        <section className="pt-12 text-center sm:pt-14">
          <p className="kicker rise justify-center">Profil de membre</p>
          <h1 className="gk-display rise mt-4 text-[clamp(28px,5vw,40px)] leading-[1.02] font-bold tracking-[-0.035em] uppercase [animation-delay:0.08s]">
            Profil <span className="outline-txt">introuvable</span>
          </h1>
          <p className="rise mt-4 text-[14px] text-ink-2 [animation-delay:0.16s]">
            Ce profil n&apos;existe pas ou n&apos;est pas public.
          </p>
        </section>
      </main>
    );
  }

  const socials = parseSocials(row.socials);
  const age = ageFromBirthDate(row.birth_date);
  const facts: [string, string][] = [
    ...(row.job_title
      ? ([["Emploi", row.company ? `${row.job_title} · ${row.company}` : row.job_title]] as [string, string][])
      : row.company
        ? ([["Entreprise", row.company]] as [string, string][])
        : []),
    ...(row.city ? ([["Ville", row.city]] as [string, string][]) : []),
    ...(age !== null ? ([["Âge", `${age} ans`]] as [string, string][]) : []),
    ["Membre depuis", fmtDate(row.created_at)],
    ["KA-ID", row.ka_id ?? "—"],
  ];

  return (
    <main className="mx-auto max-w-md px-4 pb-16 sm:px-6">
      <section className="pt-10 text-center sm:pt-12">
        <p className="kicker rise justify-center">
          Profil de membre · Groupe KA
        </p>

        <div className="rise mt-7 flex justify-center [animation-delay:0.08s]">
          {row.avatar_url ? (
            // eslint-disable-next-line @next/next/no-img-element
            <img
              src={row.avatar_url}
              alt={`Photo de ${row.name}`}
              width={176}
              height={176}
              referrerPolicy="no-referrer"
              className="h-44 w-44 rounded-full border-[3px] border-ink object-cover shadow-[8px_8px_0_rgba(20,24,20,0.18)]"
            />
          ) : (
            <span className="gk-display flex h-44 w-44 items-center justify-center rounded-full border-[3px] border-ink bg-lime text-[64px] font-bold shadow-[8px_8px_0_rgba(20,24,20,0.18)]">
              {row.name.charAt(0).toUpperCase()}
            </span>
          )}
        </div>

        <h1 className="gk-display rise mt-6 text-[clamp(28px,6vw,42px)] leading-[1.02] font-bold tracking-[-0.03em] [animation-delay:0.14s]">
          {row.name}
        </h1>
        {roleCard(row.role) && (
          <p className="rise mt-3 [animation-delay:0.18s]">
            <span className="gk-mono inline-block -rotate-1 rounded-[5px] bg-ink px-3 py-[4px] text-[10.5px] font-bold tracking-[0.12em] text-lime">
              {roleCard(row.role)}
            </span>
          </p>
        )}
        {row.bio && (
          <p className="rise mx-auto mt-4 max-w-sm text-[14.5px] leading-relaxed text-ink-2 [animation-delay:0.22s]">
            {row.bio}
          </p>
        )}

        <div className="gk-card rise mt-7 p-0 text-left [animation-delay:0.26s]">
          {facts.map(([label, value], i) => (
            <div
              key={label}
              className={`flex items-baseline justify-between gap-4 px-5 py-[13px] ${i < facts.length - 1 ? "border-b border-dashed border-[rgba(20,24,20,0.18)]" : ""}`}
            >
              <span className="klabel flex-none">{label}</span>
              <span
                className={`text-right text-[13.5px] font-semibold ${label === "KA-ID" ? "gk-mono text-green" : ""}`}
              >
                {value}
              </span>
            </div>
          ))}
        </div>

        {(row.website || Object.keys(socials).length > 0) && (
          <div className="rise mt-5 flex flex-wrap justify-center gap-2 [animation-delay:0.32s]">
            {row.website && (
              <a
                href={row.website}
                target="_blank"
                rel="noopener noreferrer nofollow"
                className="stat-chip !text-[11.5px] hover:bg-lime-soft"
              >
                🌐 Site web
              </a>
            )}
            {Object.entries(socials).map(([k, v]) => (
              <a
                key={k}
                href={socialHref(k, v)}
                target="_blank"
                rel="noopener noreferrer nofollow"
                className="stat-chip !text-[11.5px] hover:bg-lime-soft"
              >
                {SOCIAL_LABELS[k] ?? k}
              </a>
            ))}
          </div>
        )}

        <p className="mt-6 text-[12px] text-ink-2">
          Profil publié volontairement par ce membre —{" "}
          <a href={`/m/${row.ka_id}`} className="underline underline-offset-4">
            vérifier son KA-ID
          </a>
          . Courriel et téléphone jamais affichés.
        </p>
      </section>
    </main>
  );
}
